package com.example.stray_animal_management_system.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.stray_animal_management_system.admin.service.NewsService;
import com.example.stray_animal_management_system.entity.News;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description:
 * @author: panpan
 * @time: 2025/11/1
 */
@RestController
@RequestMapping("/api/news")
public class NewsController {

    @Autowired
    private NewsService newsService;

    /**
     *
     * 查询新闻
     */
    @GetMapping("/list")
    public IPage<News> list(@RequestParam(defaultValue = "1") int page,
                            @RequestParam(defaultValue = "10") int size) {
        Page<News> p = new Page<>(page, size);
        return newsService.page(p, Wrappers.<News>lambdaQuery().orderByDesc(News::getPublishTime));
    }

    /**
     *
     * 添加新闻
     */
    @PostMapping("/add")
    public String add(@RequestBody News news) {
        newsService.save(news);
        return "添加成功";
    }

    /**
     *
     * 更新新闻
     */
    @PutMapping("/update/{id}")
    public String update(@PathVariable Integer id, @RequestBody News news) {
        news.setId(id);
        newsService.updateById(news);
        return "更新成功";
    }

    /**
     *
     * 删除新闻
     */
    @DeleteMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        newsService.removeById(id);
        return "删除成功";
    }



    /**
     * 上传多张新闻图片
     */
    private static final String UPLOAD_DIR = System.getProperty("user.dir") + "/uploads/news/";

    /**
     * 上传多张新闻图片
     */
    @PostMapping("/upload")
    public Map<String, Object> uploadFiles(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam(value = "type", required = false, defaultValue = "general") String type
    ) {
        Map<String, Object> res = new HashMap<>();

        if (files == null || files.length == 0) {
            res.put("code", 400);
            res.put("msg", "文件为空");
            return res;
        }

        // 保存路径：/uploads/news/{type}/yyyyMMdd/
        String datePath = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String savePath = UPLOAD_DIR + type + "/" + datePath + "/";
        File dir = new File(savePath);
        if (!dir.exists() && !dir.mkdirs()) {
            res.put("code", 500);
            res.put("msg", "目录创建失败");
            return res;
        }

        List<String> urls = new ArrayList<>();

        for (MultipartFile file : files) {
            if (file.isEmpty()) continue;
            try {
                String originalFilename = file.getOriginalFilename();
                String extension = "";
                if (originalFilename != null && originalFilename.contains(".")) {
                    extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                }

                String fileName = UUID.randomUUID() + "_" + System.currentTimeMillis() + extension;
                File dest = new File(savePath + fileName);
                file.transferTo(dest);

                // 对应的访问 URL（与静态映射路径对应）
                String relativePath = "/uploads/news/" + type + "/" + datePath + "/" + fileName;
                String fileUrl = "http://localhost:8080" + relativePath;
                urls.add(fileUrl);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (urls.isEmpty()) {
            res.put("code", 500);
            res.put("msg", "没有文件上传成功");
            return res;
        }

        res.put("code", 200);
        res.put("msg", "上传成功");
        res.put("urls", urls);
        res.put("joinedUrls", String.join(",", urls));
        return res;
    }

    /**
     * 上传封面图片（单张）
     */
    @PostMapping("/uploadCover")
    public Map<String, Object> uploadCover(@RequestParam("file") MultipartFile file) {
        Map<String, Object> res = new HashMap<>();

        if (file.isEmpty()) {
            res.put("code", 400);
            res.put("msg", "文件为空");
            return res;
        }

        String datePath = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String savePath = UPLOAD_DIR + "cover/" + datePath + "/";
        File dir = new File(savePath);
        if (!dir.exists() && !dir.mkdirs()) {
            res.put("code", 500);
            res.put("msg", "目录创建失败");
            return res;
        }

        try {
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            String fileName = UUID.randomUUID() + "_" + System.currentTimeMillis() + extension;
            File dest = new File(savePath + fileName);
            file.transferTo(dest);

            // 访问路径（前端使用）
            String relativePath = "/uploads/news/cover/" + datePath + "/" + fileName;
            String fileUrl = "http://localhost:8080" + relativePath;

            res.put("code", 200);
            res.put("msg", "上传成功");
            res.put("url", fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
            res.put("code", 500);
            res.put("msg", "上传失败：" + e.getMessage());
        }

        return res;
    }

    /**
     *
     * 用户端获取新闻
     */
    @GetMapping("/publicList")
    public IPage<News> publicList(@RequestParam(defaultValue = "1") int page,
                                  @RequestParam(defaultValue = "6") int size,
                                  @RequestParam(required = false) String category) {
        LambdaQueryWrapper<News> wrapper = Wrappers.<News>lambdaQuery()
                .eq(News::getStatus, 1)
                .orderByDesc(News::getIsTop)
                .orderByDesc(News::getPublishTime);
        if (category != null && !category.isEmpty()) {
            wrapper.eq(News::getCategoryName, category);
        }
        return newsService.page(new Page<>(page, size), wrapper);
    }

    /**
     *
     * 用户端新闻详情
     */
    @GetMapping("/detail/{id}")
    public Map<String, Object> detail(@PathVariable Integer id) {
        Map<String, Object> res = new HashMap<>();
        News news = newsService.getById(id);
        if (news == null) {
            res.put("code", 404);
            res.put("msg", "新闻不存在");
            return res;
        }
        // 浏览量 +1
        news.setViews(news.getViews() + 1);
        newsService.updateById(news);

        res.put("code", 200);
        res.put("data", news);
        return res;
    }


}
